/*
 * ColConfigFrame.java
 *
 * --- Last Update: 6/20/2010 3:12 PM ---
 *
 * Update Notes 6/20/2010 3:12 PM by Adrian Wijasa:
 * Changed any mention of Oracle into Database.
 *
 * Update Notes 6/18/2010 8:57 PM by Adrian Wijasa:
 * Changed the name of this class from OracleFrame to ColConfigFrame.
 *
 * Update Notes 5/17/2010 9:39 PM by Adrian Wijasa:
 * This class is now compatible with MySQL.
 * Added getRegex( String searchText ) method.
 * Displays all schemas.
 * Added a Show Only interface to filter out unwanted schemas, tables, and columns.
 *
 * Update Notes 5/16/2010 6:42 PM by Adrian Wijasa:
 * Displays all schemas found in the database instead of just ALUMNI, GENERAL, SATURN, PAYROLL, and user schema.
 *
 * Update Notes 4/22/2010 9:12 PM by Adrian Wijasa:
 * Now is able to work with Banner PAYROLL schema.
 *
 * Update Notes 3/26/2010 4:41 PM by Adrian Wijasa:
 * Changed the title of this form to from Oracle Columns Selector to Oracle Column Selector.
 *
 * Update Notes 3/22/2010 4:59 PM by Adrian Wijasa:
 * Re-adjusted the form design so that it will look good under Java Metal UI.
 *
 * Update Notes 1/23/2010 2:57 PM by Adrian Wijasa:
 * Added IA_ADMIN schema to this CSV Loader window.
 *
 * Created on March 12, 2007, 1:50 PM
 *
 * CSV Loader
 * Copyright 2007, 2009, 2010 Adrian Wijasa
 *
 * This file is part of CSV Loader.
 *
 * CSV Loader is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * CSV Loader is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with CSV Loader.  If not, see <http://www.gnu.org/licenses/>.
 */

package forms;

import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import sql.MetaDataQuery;
import tree.ColumnNode;
import tree.SchemaNode;
import tree.TableNode;

/**
 * A CSV Loader window that is used to associate the CSV columns to Oracle columns.
 *
 * @author matianyuan
 */
public class ColConfigFrame extends javax.swing.JFrame {

    /** Creates new form ColConfigFrame */
    public ColConfigFrame( Main main ) throws ClassNotFoundException, SQLException {
        this.main = main;
        initComponents();
        initMetaData();
        initTree();
        initList();
        setLocation( main.getX(), main.getY() );
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        treeScrollPane = new javax.swing.JScrollPane();
        tree = new javax.swing.JTree();
        listScrollPane = new javax.swing.JScrollPane();
        list = new javax.swing.JList();
        saveLabel = new javax.swing.JLabel();
        resetLabel = new javax.swing.JLabel();
        addLabel = new javax.swing.JLabel();
        removeLabel = new javax.swing.JLabel();
        searchPanel = new javax.swing.JPanel();
        showOnlyLabel = new javax.swing.JLabel();
        schemaTextField = new javax.swing.JTextField();
        schemaLabel = new javax.swing.JLabel();
        tableTextField = new javax.swing.JTextField();
        tableLabel = new javax.swing.JLabel();
        columnTextField = new javax.swing.JTextField();
        columnLabel = new javax.swing.JLabel();
        goLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Database Column Selector");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        tree.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                treeMouseClicked(evt);
            }
        });
        treeScrollPane.setViewportView(tree);

        listScrollPane.setViewportView(list);

        saveLabel.setFont(new java.awt.Font("Dialog", 1, 11));
        saveLabel.setForeground(new java.awt.Color(0, 102, 255));
        saveLabel.setText("Save");
        saveLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                saveLabelMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                saveLabelMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                saveLabelMouseExited(evt);
            }
        });

        resetLabel.setFont(new java.awt.Font("Dialog", 1, 11));
        resetLabel.setForeground(new java.awt.Color(0, 102, 255));
        resetLabel.setText("Reset");
        resetLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                resetLabelMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                resetLabelMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                resetLabelMouseExited(evt);
            }
        });

        addLabel.setFont(new java.awt.Font("Dialog", 1, 11));
        addLabel.setForeground(new java.awt.Color(0, 102, 255));
        addLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        addLabel.setText("Add >");
        addLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                addLabelMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                addLabelMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                addLabelMouseExited(evt);
            }
        });

        removeLabel.setFont(new java.awt.Font("Dialog", 1, 11));
        removeLabel.setForeground(new java.awt.Color(0, 102, 255));
        removeLabel.setText("Remove");
        removeLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                removeLabelMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                removeLabelMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                removeLabelMouseExited(evt);
            }
        });

        showOnlyLabel.setFont(new java.awt.Font("Dialog", 0, 12));
        showOnlyLabel.setText("Show Only: ");

        schemaLabel.setFont(new java.awt.Font("Dialog", 0, 9));
        schemaLabel.setText("Schema");

        tableLabel.setFont(new java.awt.Font("Dialog", 0, 9));
        tableLabel.setText("Table");

        columnLabel.setFont(new java.awt.Font("Dialog", 0, 9));
        columnLabel.setText("Column");

        goLabel.setFont(new java.awt.Font("Dialog", 1, 11));
        goLabel.setForeground(new java.awt.Color(0, 102, 255));
        goLabel.setText("Go");
        goLabel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                goLabelMouseClicked(evt);
            }
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                goLabelMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                goLabelMouseExited(evt);
            }
        });

        org.jdesktop.layout.GroupLayout searchPanelLayout = new org.jdesktop.layout.GroupLayout(searchPanel);
        searchPanel.setLayout(searchPanelLayout);
        searchPanelLayout.setHorizontalGroup(
            searchPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(searchPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(showOnlyLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 82, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(searchPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(schemaTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 55, Short.MAX_VALUE)
                    .add(schemaLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 55, Short.MAX_VALUE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(searchPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(tableTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 54, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(tableLabel))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(searchPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(columnTextField, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 52, Short.MAX_VALUE)
                    .add(columnLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 52, Short.MAX_VALUE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(goLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 19, Short.MAX_VALUE)
                .add(48, 48, 48))
        );
        searchPanelLayout.setVerticalGroup(
            searchPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(searchPanelLayout.createSequentialGroup()
                .add(searchPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(searchPanelLayout.createSequentialGroup()
                        .add(4, 4, 4)
                        .add(showOnlyLabel))
                    .add(searchPanelLayout.createSequentialGroup()
                        .add(4, 4, 4)
                        .add(goLabel))
                    .add(searchPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(schemaTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(tableTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(columnTextField, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(searchPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE, false)
                    .add(schemaLabel)
                    .add(tableLabel)
                    .add(columnLabel)))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(searchPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(59, 59, 59))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(layout.createSequentialGroup()
                                .add(319, 319, 319)
                                .add(saveLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE))
                            .add(treeScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 350, Short.MAX_VALUE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(addLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 57, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(removeLabel))
                        .add(4, 4, 4)))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(listScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 347, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(resetLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 36, Short.MAX_VALUE)
                        .add(311, 311, 311)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(org.jdesktop.layout.GroupLayout.LEADING, listScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 567, Short.MAX_VALUE)
                    .add(layout.createSequentialGroup()
                        .add(searchPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                            .add(treeScrollPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 523, Short.MAX_VALUE)
                            .add(layout.createSequentialGroup()
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 211, Short.MAX_VALUE)
                                .add(addLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 14, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                                .add(removeLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 13, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .add(273, 273, 273)))))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(resetLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(saveLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void treeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_treeMouseClicked
        if( evt.getClickCount() == 2 ) { // Double Click
            try {
                TreePath selectionPath = tree.getSelectionPath();
                DefaultMutableTreeNode lastPathComp = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
                String lastPathCompStr = lastPathComp.toString();

                /* Schema Node Clicked */
                if( lastPathComp instanceof SchemaNode && lastPathComp.isLeaf() ) {
                    ArrayList<String> tableList = metaDataQuery.getTables( lastPathCompStr );

                    for( int i = 0; i < tableList.size(); i++ ) {
                        String tableFilter = getRegex( tableTextField.getText() );

                        if( tableList.get( i ).toLowerCase().matches( tableFilter ) )
                            lastPathComp.add( new TableNode( tableList.get( i ) ) );
                    }

                    tree.expandPath( selectionPath );
                }

                /* Table Node Clicked */
                else if( lastPathComp instanceof TableNode && lastPathComp.isLeaf() ) {
                    String schema;
                    
                    if( main.dbType.equals( "MySQL" ) )
                        schema = null;
                    else
                        schema = selectionPath.getPathComponent( 1 ).toString();

                    ArrayList<String> columnList = metaDataQuery.getColumns( schema, lastPathCompStr );
                    ArrayList<String> notNullColumnList = metaDataQuery.getNotNullColumns( schema, lastPathCompStr );
                    ArrayList<String> pkList = metaDataQuery.getPrimaryKeys( schema, lastPathCompStr );

                    /* List Table Primary Keys */
                    DefaultMutableTreeNode pkNode = new DefaultMutableTreeNode( "Primary Keys" );
                    lastPathComp.add( pkNode );

                    String columnFilter = getRegex( columnTextField.getText() );

                    for( int i = 0; i < pkList.size(); i++ ) {
                        if( pkList.get( i ).toLowerCase().matches( columnFilter ) )
                            pkNode.add( new ColumnNode( pkList.get( i ) ) );
                    }

                    /* List Table Not Null Columns that are not Primary Keys */
                    DefaultMutableTreeNode notNullNode = new DefaultMutableTreeNode( "Not Null" );
                    lastPathComp.add( notNullNode );

                    for( int i = 0; i < notNullColumnList.size(); i++ ) {
                        column = notNullColumnList.get( i );

                        if( !pkList.contains( column ) )
                            if( column.toLowerCase().matches( columnFilter ) )
                                notNullNode.add( new ColumnNode( column ) );
                    }

                    /* List Table Nullable Columns */
                    DefaultMutableTreeNode nullNode = new DefaultMutableTreeNode( "Nullable" );
                    lastPathComp.add( nullNode );

                    for( int i = 0; i < columnList.size(); i++ ) {
                        column = columnList.get( i );

                        if( !notNullColumnList.contains( column ) )
                            if( column.toLowerCase().matches( columnFilter ) )
                                nullNode.add( new ColumnNode( column ) );
                    }

                    tree.expandPath( selectionPath );
                }

                /* Column Node Clicked */
                else if( lastPathComp instanceof ColumnNode ) {
                    addSelectedNodesToList();
                }
            } catch( SQLException e ) {
                try {
                    metaDataQuery.closeConnection();
                } catch( SQLException se ) {}

                JOptionPane.showMessageDialog( null, e.getMessage(), "SQL Error", JOptionPane.ERROR_MESSAGE );
            } catch( NullPointerException ne ) {}
        }
}//GEN-LAST:event_treeMouseClicked

    private void saveLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveLabelMouseClicked
        saveLabel.setForeground( main.red );

        main.csvPanel.setSqlListData( listArrayList );

        dispose();
}//GEN-LAST:event_saveLabelMouseClicked

    private void saveLabelMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveLabelMouseExited
        saveLabel.setForeground( main.blue );
}//GEN-LAST:event_saveLabelMouseExited

    private void saveLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_saveLabelMouseEntered
        saveLabel.setForeground( main.black );
}//GEN-LAST:event_saveLabelMouseEntered

    private void resetLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_resetLabelMouseClicked
        resetLabel.setForeground( main.red );

        listArrayList = new ArrayList<String>( main.csvPanel.listArrayList );
        list.setListData( listArrayList.toArray() );
}//GEN-LAST:event_resetLabelMouseClicked

    private void resetLabelMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_resetLabelMouseExited
        resetLabel.setForeground( main.blue );
}//GEN-LAST:event_resetLabelMouseExited

    private void resetLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_resetLabelMouseEntered
        resetLabel.setForeground( main.black );
}//GEN-LAST:event_resetLabelMouseEntered

    private void addLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addLabelMouseClicked
        addLabel.setForeground( main.red );

        addSelectedNodesToList();
}//GEN-LAST:event_addLabelMouseClicked

    private void addLabelMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addLabelMouseExited
        addLabel.setForeground( main.blue );
}//GEN-LAST:event_addLabelMouseExited

    private void addLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_addLabelMouseEntered
        addLabel.setForeground( main.black );
}//GEN-LAST:event_addLabelMouseEntered

    private void removeLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_removeLabelMouseClicked
        removeLabel.setForeground( main.red );

        Object toRemoveVals[] = list.getSelectedValues();

        if( toRemoveVals != null ) {
            for( int i = 0; i < toRemoveVals.length; i++ ) {
                listArrayList.remove( "" + toRemoveVals[i] );
            }

            list.setListData( listArrayList.toArray() );
        }
}//GEN-LAST:event_removeLabelMouseClicked

    private void removeLabelMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_removeLabelMouseExited
        removeLabel.setForeground( main.blue );
}//GEN-LAST:event_removeLabelMouseExited

    private void removeLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_removeLabelMouseEntered
        removeLabel.setForeground( main.black );
}//GEN-LAST:event_removeLabelMouseEntered

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        try {
            metaDataQuery.closeConnection();
        }
        catch( SQLException e ) {}

        main.setEnabled( true );
        main.requestFocus();
    }//GEN-LAST:event_formWindowClosed

    private void goLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_goLabelMouseEntered
        goLabel.setForeground( main.black );
    }//GEN-LAST:event_goLabelMouseEntered

    private void goLabelMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_goLabelMouseExited
        goLabel.setForeground( main.blue );
    }//GEN-LAST:event_goLabelMouseExited

    private void goLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_goLabelMouseClicked
        goLabel.setForeground( main.red );
        try {
            initTree();
        }
        catch( SQLException e ) {
            try {
                metaDataQuery.closeConnection();
            }
            catch( SQLException se ) {}
            
            JOptionPane.showMessageDialog( null, e.getMessage(), "SQL Error", JOptionPane.ERROR_MESSAGE );
        }
    }//GEN-LAST:event_goLabelMouseClicked

    private void addSelectedNodesToList() { // Add only Column Nodes into JList
        TreePath[] treePath = tree.getSelectionPaths();
        DefaultMutableTreeNode lastPathComp;

        if( treePath != null ) {
            for( int i = 0; i < treePath.length; i++ ) {
                lastPathComp = (DefaultMutableTreeNode)treePath[i].getLastPathComponent();

                if( lastPathComp instanceof ColumnNode ) {
                    if( main.dbType.equals( "MySQL" ) )
                        column = treePath[i].getPathComponent( 1 ).toString() + " > " + lastPathComp.toString();
                    else
                        column = treePath[i].getPathComponent( 1 ).toString() + " > " + treePath[i].getPathComponent( 2 ).toString() + " > " + lastPathComp.toString();

                    if( !listArrayList.contains( column ) ) {
                        boolean usedColumn = false;

                        for( int j = 0; j < main.csvPanel.currentImage.sqlArrayList.size(); j++ ) {
                            if( j != main.csvPanel.selectedColIndex && main.csvPanel.currentImage.sqlArrayList.get( j ).contains( column ) ) {
                                JOptionPane.showMessageDialog( null, column + " will be uploaded by Column " + main.csvPanel.selectedColIndex, "Failed to add " + column, JOptionPane.ERROR_MESSAGE );
                                usedColumn = true;
                                break;
                            }
                        }

                        if( !usedColumn )
                            listArrayList.add( column );
                    }
                }
            }

            list.setListData( listArrayList.toArray() );
        }
    }

    /* Converts searchText into a regex, ? will be changed to ., and * will be changed to .* */
    private String getRegex( String searchText ) {
        return ".*" + searchText.toLowerCase().replace( '?', '.' ).replace( "*", ".*" ) + ".*";
    }

    private void initList() {
        listArrayList = new ArrayList<String>( main.csvPanel.listArrayList );
        list.setListData( listArrayList.toArray() );
    }

    private void initMetaData() throws ClassNotFoundException, SQLException { // Connect to Database
        metaDataQuery = new MetaDataQuery( main );
    }

    private void initTree() throws SQLException {
        rootNode = new DefaultMutableTreeNode( main.sid );

        if( main.dbType.equals( "MySQL" ) ) {
            for( String table: metaDataQuery.getTables( null ) ) {
                String tableFilter = getRegex( tableTextField.getText() );

                if( table.toLowerCase().matches( tableFilter ) )
                    rootNode.add( new TableNode( table ) );
            }
        }
        else {
            for( String schema: metaDataQuery.getSchemas() ) {
                String schemaFilter = getRegex( schemaTextField.getText() );

                if( schema.toLowerCase().matches( schemaFilter ) )
                    rootNode.add( new SchemaNode( schema ) );
            }
        }

        tree.setModel( new DefaultTreeModel( rootNode ) );
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel addLabel;
    private javax.swing.JLabel columnLabel;
    private javax.swing.JTextField columnTextField;
    private javax.swing.JLabel goLabel;
    private javax.swing.JList list;
    private javax.swing.JScrollPane listScrollPane;
    private javax.swing.JLabel removeLabel;
    private javax.swing.JLabel resetLabel;
    private javax.swing.JLabel saveLabel;
    private javax.swing.JLabel schemaLabel;
    private javax.swing.JTextField schemaTextField;
    private javax.swing.JPanel searchPanel;
    private javax.swing.JLabel showOnlyLabel;
    private javax.swing.JLabel tableLabel;
    private javax.swing.JTextField tableTextField;
    private javax.swing.JTree tree;
    private javax.swing.JScrollPane treeScrollPane;
    // End of variables declaration//GEN-END:variables

    private DefaultMutableTreeNode rootNode;
    private Main main;
    private MetaDataQuery metaDataQuery;
    private String column;
    private ArrayList<String> listArrayList;
}
